'use client'
import React, { useState, useEffect } from 'react';

// 定义留言数据类型
interface MessageData {
    id: string;
    name: string;
    phone: string;
    email: string;
    content: string;
    timestamp: string;
}

export default function MessagesPage() {
    const [allMessages, setAllMessages] = useState<MessageData[]>([]); // 完整的原始留言列表
    const [displayedMessages, setDisplayedMessages] = useState<MessageData[]>([]); // 当前显示的留言列表
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [searchTerm, setSearchTerm] = useState('');

    // 加载留言数据
    const loadMessages = async () => {
        setLoading(true);
        setError(null);
        try {
            const response = await fetch('/api/contact');
            const result = await response.json();
            if (result.success) {
                const messages = result.data || [];
                setAllMessages(messages);
                setDisplayedMessages(messages); // 默认显示所有留言
            } else {
                setError(result.message || '加载失败');
            }
        } catch (err) {
            console.error('加载留言失败:', err);
            setError('加载失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    // 格式化日期
    const formatDate = (dateString: string) => {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
        });
    };

    // 处理搜索
    const handleSearch = () => {
        if (!searchTerm.trim()) {
            setDisplayedMessages(allMessages); // 如果搜索框为空，显示所有留言
            return;
        }
        // 对搜索词进行标准化处理（转换为小写并trim空格）
        const normalizedSearchTerm = searchTerm.toLowerCase().trim();
        // 始终基于完整的原始留言列表进行过滤
        const filteredMessages = allMessages.filter((message) =>
            message.name.includes(normalizedSearchTerm) ||
            message.phone.includes(normalizedSearchTerm) ||
            message.email.includes(normalizedSearchTerm) ||
            message.content.includes(normalizedSearchTerm)
        );
        setDisplayedMessages(filteredMessages);
    };

    // 组件挂载时加载数据
    useEffect(() => {
        loadMessages();
    }, []);

    return (
        <div className='max-w-4xl mx-auto p-6 bg-white dark:bg-gray-900 rounded-xl shadow-md border border-gray-200 dark:border-gray-800 mt-8'>
            <h1 className='text-2xl font-bold mb-6 text-center text-gray-900 dark:text-white'>留言列表</h1>
            <div className='flex justify-center mb-4 space-x-4'>
                <input
                    type='text'
                    placeholder='搜索留言...'
                    className='px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary dark:bg-gray-800 dark:text-white'
                    onChange={(e) => setSearchTerm(e.target.value)}
                    value={searchTerm}
                />
                <button className='px-4 py-2 bg-primary/90 text-white rounded-lg hover:bg-primary transition-colors' onClick={handleSearch}>
                    搜索
                </button>
            </div>
            {loading ? (
                <div className='text-center py-8'>加载中...</div>
            ) : error ? (
                <div className='text-center py-8 text-red-500'>{error}</div>
            ) : displayedMessages.length === 0 ? (
                <div className='text-center py-8 text-gray-500'>暂无留言</div>
            ) : (
                <div className='space-y-6'>
                    {displayedMessages.map((message) => (
                        <div
                            key={message.id}
                            className='p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:shadow-md transition-shadow'
                        >
                            <div className='flex justify-between items-center mb-2'>
                                <h3 className='font-bold text-gray-900 dark:text-white'>{message.name}</h3>
                                <span className='text-sm text-gray-500 dark:text-gray-400'>
                                    {formatDate(message.timestamp)}
                                </span>
                            </div>
                            <p className='text-gray-700 dark:text-gray-300 mb-4'>{message.content}</p>
                            <div className='text-sm text-gray-500 dark:text-gray-400'>
                                <div>邮箱: {message.email}</div>
                                <div>电话: {message.phone}</div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}